package com.sq.springcloud.controller;

import com.sq.springcloud.entities.CommontResult;
import com.sq.springcloud.entities.Payment;
import com.sq.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @author: ydy
 * @date: 2022年09月01日 17:06
 */
@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/add")
    public CommontResult add(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("插入结果：" + result);
        if(result > 0){
            return new CommontResult(200, "插入数据库成功,serverPort:" + serverPort, result);
        }else{
            return new CommontResult(444, "插入数据库失败", null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommontResult queryById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById((long) id);
        log.info("查询结果：" + payment);
        if(payment != null){
            return new CommontResult<Payment>(200, "查询成功,serverPort:" + serverPort, payment);
        }else{
            return new CommontResult<Payment>(444, "没有查询到指定数据", null);
        }
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        //得到注册到Eureka中的所有服务清单列表
        //"cloud-payment-service"
        //"cloud-order-service"
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("******service:" + service);
        }

        //得到某一个微服务名称下的所有实例，因为集群采用统一名称注册到了Eureka中
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        //CLOUD-PAYMENT-SERVICE	192.168.109.2	8001	http://192.168.109.2:8001
        //CLOUD-PAYMENT-SERVICE	192.168.109.2   8002	http://192.168.109.2:8002
        for (ServiceInstance instance : instances) {
            log.info("******instance:" + instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return discoveryClient;
    }

    @GetMapping(value = "payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {  //InterruptedException：中断异常
            e.printStackTrace();
        }
        return serverPort;
    }
}
